<?php
class MemcacheProxy {
	/**
	 * 
	 * Cache 详见MI_Cache
	 * 
	 */
	const CACHE_TIME = 1;
	private static $_memcache;
	public static function Cache() {
		if (! is_object ( self::$_memcache )) {
			global $MEMCACHE_CONFIG;
			$config = $MEMCACHE_CONFIG ['mem_config'];
			self::$_memcache = MI_Cache::instance ( $config );
		}
		return self::$_memcache;
	}
	
	/**
	 * 根据key值获取cache中的值
	 * @param $key 
	 * @return array||bool
	 * **/
	public static function getCache($key) {
		$cache_obj = self::Cache ();
		if ($key) {
			$data = $cache_obj->get ( $key );
			if ($data) {
				return $data;
			}
		}
		return false;
	}
	
	/**
	 * 设置cache
	 * @param $key	
	 * @param $result	需要设置的值
	 * @param $time		cache存活时间
	 * @return bool
	 * **/
	public static function addCache($key, $result, $time = self::CACHE_TIME) {
		$cache_obj = self::Cache ();
		if ($key && $result) {
			$data = $cache_obj->get ( $key );
			if ($data) {
				return $cache_obj->replace ( $key, $result, $time );
			} else {
				return $cache_obj->add ( $key, $result, $time );
			}
		}
		return false;
	}

	/**
	 * 递增cache值
	 * @param $key
	 * @param $offset
	 */
	public static function incCache($key, $time, $offset = 1) {
		$cache_obj = self::Cache ();
		if ($key) {
			$data = $cache_obj->get ( $key );
			if ($data) {
				return $cache_obj->inc ( $key, $offset );
			} else {
				return $cache_obj->add ( $key, 1, $time );
			}
		}
		return false;
	}
	
}
